import 'dart:convert';
import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:go_router/go_router.dart';
import 'package:webview_flutter/webview_flutter.dart';

class WebViewPage extends StatefulWidget {
  final String? url;
  final String? title;
  final bool isLocalUrl;

  WebViewPage({this.url, this.title, this.isLocalUrl = false});

  @override
  _WebViewPage createState() => _WebViewPage();
}

class _WebViewPage extends State<WebViewPage>
    with AutomaticKeepAliveClientMixin {
  final WebViewController controller = WebViewController();

  @override
  void initState() {
    super.initState();

    controller
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..setBackgroundColor(Colors.white)
      ..setNavigationDelegate(NavigationDelegate(onProgress: (int progress) {
        debugPrint('WebView is loading (progress : $progress%)');
      }, onPageStarted: (String url) {
        debugPrint('Page started loading: $url');
      }, onPageFinished: (String url) {
        // controller.evaluateJavascript('document.title').then((title) => debugPrint(title));
      }));

    if (widget.isLocalUrl) {
      _loadHtmlAssets(controller);
    } else {
      var url = widget.isLocalUrl
          ? Uri.dataFromString(widget.url ?? '',
                  mimeType: 'text/html', encoding: Encoding.getByName('utf-8'))
              .toString()
          : widget.url;
      controller.loadRequest(Uri.parse(url!));
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: widget.title != null
          ? const BoxDecoration(
              image: DecorationImage(
                image: AssetImage('images/bg1.png'),
                fit: BoxFit.fill,
              ),
            )
          : null,
      child: Scaffold(
        backgroundColor: Colors.transparent,
        appBar: widget.title != null ? _buildAppbar() : null,
        body: _buildBody(),
      ),
    );
  }

  _buildAppbar() {
    return AppBar(
        elevation: 0,
        backgroundColor: Colors.transparent,
        title: Text(
          widget.title ?? '',
          style: const TextStyle(color: Colors.white),
        ),
        centerTitle: true,
        leading: IconButton(
            padding: const EdgeInsets.all(16),
            icon: const Icon(
              Icons.arrow_back,
              color: Colors.white,
            ),
            onPressed: () {
              context.pop();
            }));
  }

  _buildBody() {
    return Column(
      children: <Widget>[
        const SizedBox(
          height: 0.5,
          width: double.infinity,
          child:
              DecoratedBox(decoration: BoxDecoration(color: Color(0xFFEEEEEE))),
        ),
        Expanded(
          child: WebViewWidget(
            gestureRecognizers: {
              Factory<VerticalDragGestureRecognizer>(
                      () => VerticalDragGestureRecognizer())
            },
            controller: controller,
          ),
        )
      ],
    );
  }

  //加载本地文件
  _loadHtmlAssets(WebViewController controller) async {
    String htmlPath = await rootBundle.loadString(widget.url ?? '');
    var indexFile = File(htmlPath);
    controller.loadFile(htmlPath);
  }

  @override
  bool get wantKeepAlive => true;
}
